package utils

import (
	"crypto/tls"
	"fmt"
    "github.com/gogf/gf/frame/g"
    "github.com/gogf/gf/util/gconv"
    "log"
	"net"
	"net/smtp"
	"strings"
)

type EmailConf struct {
    User        string `json:"user"`
    Password    string `json:"password"`
    Host        string `json:"host"`
}

func SendToMail(to, subject, body, mailType string) error {
    var conf *EmailConf
    confSrc := g.Cfg().Get("email")
    err := gconv.Scan(confSrc, &conf)
    if err != nil {
        return err
    }

	//user := "tianye@tcreation.com.hk"
	//password := "T86GhQSX498cBh3M"
	//host := "smtp.exmail.qq.com:465"
	// host := "smtp.exmail.qq.com:25"
	hp := strings.Split(conf.Host, ":")
	auth := smtp.PlainAuth("", conf.User, conf.Password, hp[0])
	var contentType string
	var mailBody string
	if mailType == "html" {
		contentType = "Content-Type: text/" + mailType + "; charset=UTF-8"
		mailBody = `
		<html>
		<body>
		` + body + `
		</body>
		</html>
		`
	} else {
		contentType = "Content-Type: text/plain" + "; charset=UTF-8"
		mailBody = body
	}

	msg := []byte("To: " + to + "\r\nFrom: " + conf.User + ">\r\nSubject: " + subject + "\r\n" + contentType + "\r\n\r\n" + mailBody)
	sendTo := strings.Split(to, ";")
	// err := smtp.SendMail(host, auth, user, sendTo, msg)
	err = SendMailUsingTLS(conf.Host, auth, conf.User, sendTo, msg)
	return err
}

func MailExample() error {
	to := "315959139@qq.com"
	subject := "使用Golang发送邮件"
	body := "Test send to email"
	fmt.Println("send email")
	err := SendToMail(to, subject, body, "html")
	if err != nil {
		fmt.Println("Send mail error!")
		fmt.Println(err)
	} else {
		fmt.Println("Send mail success!")
	}
	return err
}

//return a smtp client
func Dial(addr string) (*smtp.Client, error) {
	conn, err := tls.Dial("tcp", addr, nil)
	if err != nil {
		log.Panicln("Dialing Error:", err)
		return nil, err
	}
	//分解主机端口字符串
	host, _, _ := net.SplitHostPort(addr)
	return smtp.NewClient(conn, host)
}

//参考net/smtp的func SendMail()
//使用net.Dial连接tls(ssl)端口时,smtp.NewClient()会卡住且不提示err
//len(to)>1时,to[1]开始提示是密送
func SendMailUsingTLS(addr string, auth smtp.Auth, from string,
	to []string, msg []byte) (err error) {

	//create smtp client
	c, err := Dial(addr)
	if err != nil {
		log.Println("Create smpt client error:", err)
		return err
	}
	defer c.Close()

	if auth != nil {
		if ok, _ := c.Extension("AUTH"); ok {
			if err = c.Auth(auth); err != nil {
				log.Println("Error during AUTH", err)
				return err
			}
		}
	}

	if err = c.Mail(from); err != nil {
		return err
	}

	for _, addr := range to {
		if err = c.Rcpt(addr); err != nil {
			return err
		}
	}

	w, err := c.Data()
	if err != nil {
		return err
	}

	_, err = w.Write(msg)
	if err != nil {
		return err
	}

	err = w.Close()
	if err != nil {
		return err
	}
	return c.Quit()
}
